using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyAI : MonoBehaviour
{
    public EnemyData enemyData;
    public float detectionRange = 10f;
    public float attackRange = 2f;
    public float moveSpeed = 3f;
    public float attackCooldown = 1f;

    private Transform player;
    private EnemyState currentState;
    private float cooldownTimer;
    private Vector3 patrolDestination;
    private float patrolWaitTime = 2f;
    private float patrolTimer;

    private void Awake()
    {
        player = GameObject.FindGameObjectWithTag("Player").transform;
        currentState = EnemyState.Patrolling;

        // Set patrol destination
        SetRandomPatrolDestination();
    }

    private void Update()
    {
        if (player == null) return;

        UpdateTimers();

        switch (currentState)
        {
            case EnemyState.Patrolling:
                HandlePatrolling();
                break;
            case EnemyState.Chasing:
                HandleChasing();
                break;
            case EnemyState.Attacking:
                HandleAttacking();
                break;
        }

        // ״̬ת�����
        CheckStateTransitions();
    }

    private void CheckStateTransitions()
    {
        float distanceToPlayer = Vector3.Distance(transform.position, player.position);

        if (distanceToPlayer <= attackRange)
        {
            currentState = EnemyState.Attacking;
        }
        else if (distanceToPlayer <= detectionRange)
        {
            currentState = EnemyState.Chasing;
        }
        else
        {
            currentState = EnemyState.Patrolling;
        }
    }

    private void HandlePatrolling()
    {
        // Move to patrol destination
        if (Vector3.Distance(transform.position, patrolDestination) > 0.5f)
        {
            MoveTowards(patrolDestination);
        }
        else
        {
            // Wait time
            patrolTimer += Time.deltaTime;
            if (patrolTimer >= patrolWaitTime)
            {
                SetRandomPatrolDestination();
                patrolTimer = 0;
            }
        }
    }

    private void HandleChasing()
    {
        MoveTowards(player.position);
    }

    private void HandleAttacking()
    {
        // �������
        transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));

        if (cooldownTimer <= 0)
        {
            Attack();
            cooldownTimer = attackCooldown;
        }
    }

    private void MoveTowards(Vector3 target)
    {
        // Keep Y axis unchanged
        Vector3 targetPosition = new Vector3(target.x, transform.position.y, target.z);

        // Move
        Vector3 direction = (targetPosition - transform.position).normalized;
        transform.position += direction * moveSpeed * Time.deltaTime;

        // Rotate towards movement direction
        transform.LookAt(targetPosition);
    }

    private void Attack()
    {
        // Play attack animation
        Animator animator = GetComponent<Animator>();
        if (animator != null)
        {
            animator.SetTrigger("Attack");
        }

        // Deal damage
        PlayerStats playerStats = player.GetComponent<PlayerStats>();
        if (playerStats != null)
        {
            playerStats.TakeDamage(enemyData.damage);
        }

        // Trigger attack event (sound, effects etc.)
        EventManager.TriggerEvent(new EnemyAttackedEvent(this));
    }

    private void SetRandomPatrolDestination()
    {
        Vector3 randomOffset = new Vector3(
            Random.Range(-5f, 5f),
            0,
            Random.Range(-5f, 5f)
        );

        patrolDestination = transform.position + randomOffset;
    }

    private void UpdateTimers()
    {
        if (cooldownTimer > 0)
        {
            cooldownTimer -= Time.deltaTime;
        }
    }
}

public enum EnemyState
{
    Patrolling,
    Chasing,
    Attacking,
    Stunned
}